﻿using GamFi.API.Application.Contracts.Token.GetUserTokens;
using GamFi.API.Application.Exceptions;
using GamFi.API.Application.Interfaces;
using GamFi.API.Application.Resources;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;

namespace GamFi.API.Application.Features.Queries.Token.GetUserTokensQuery;

public class GetUserTokensQueryHandler(IDbContext dbContext, IStringLocalizer<ExceptionMessages> localizer)
    : IRequestHandler<GetUserTokensQuery, GetUserTokensResponse>
{
    public async Task<GetUserTokensResponse> Handle(GetUserTokensQuery request, CancellationToken cancellationToken)
    {
        if (request is null)
            throw new RequestException(localizer[nameof(RequestException.RequestIsEmpty)]);

        if (!Guid.TryParse(request.UserInfoId, out var userInfoId))
            throw new RequestException(localizer[nameof(RequestException.RequestHaveBadId)]);

        var query = dbContext.Tokens.Where(u => u.CreatedBy == userInfoId);

        if (!string.IsNullOrEmpty(request.Filter))
            query = query.Where(u => u.Name.ToLower().Contains(request.Filter.ToLower()));

        query = query
            .Skip((request.PageNumber - 1) * request.PageSize)
            .Take(request.PageSize);

        var tokens = await query.Select(t =>
            new GetUserTokensResponseItem
            {
                Id = t.Id,
                Name = t.Name,
                TokenSymbol = t.TokenSymbol,
                CreatedDate = t.CreatedDate ?? DateTime.MinValue,
                ChainId = t.ChainId,
                TargetedRaise = t.TargetedRaise,
                TotalRaise = t.TotalRaise,
                ImageId = t.ImageId
            }).ToListAsync(cancellationToken);

        return new GetUserTokensResponse
        {
            Tokens = tokens,
            Count = tokens.Count
        };
    }
}